Categories
Fastify

Server-Side Development with Fastify — Route Declarations

Spread the love

Fastify is a small Node framework for developing back end web apps.

In this article, we’ll look at how to create back end apps with Fastify.

Route Declaration Shorthand

Fastify comes with shorthand methods to declare routes.

The methods include:

  • fastify.get(path, [options], handler)
  • fastify.head(path, [options], handler)
  • fastify.post(path, [options], handler)
  • fastify.put(path, [options], handler)
  • fastify.delete(path, [options], handler)
  • fastify.options(path, [options], handler)
  • fastify.patch(path, [options], handler)

For example, we can write:

const fastify = require('fastify')()

const opts = {
  schema: {
    response: {
      200: {
        type: 'object',
        properties: {
          hello: { type: 'string' }
        }
      }
    }
  }
}
fastify.get('/', opts, (request, reply) => {
  reply.send({ hello: 'world' })
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

We create the opts to set the response schema.

Then we pass that into get method as the 2nd argument of it.

We can also write:

const fastify = require('fastify')()

const opts = {
  schema: {
    response: {
      200: {
        type: 'object',
        properties: {
          hello: { type: 'string' }
        }
      }
    }
  },
  handler: function (request, reply) {
    reply.send({ hello: 'world' })
  }
}
fastify.get('/', opts)

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

to put the handler method in the opts object instead of passing it into the 3rd argument.

Url Building

Fastify supports both static and dynamic URLs.

For example, we can register a parametric path by writing:

const fastify = require('fastify')()

fastify.get('/example/:userId', (request, reply) => {
  reply.send('example')
})
fastify.get('/example/:userId/:secretToken', (request, reply) => {
  reply.send('example')
})
fastify.get('/example/*', (request, reply) => {
  reply.send('example')
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

to add the routes.

:userId and :secretToken are URL parameters.

And * is a wildcard character.

Also, we can use regex to match URL route patterns.

For example, we can write:

const fastify = require('fastify')()

fastify.get('/example/:file(^d+).png', (request, reply) => {
  reply.send('example')
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

We match the URL pattern with the (^d+) pattern.

So when we go to /example/1.png , we see the response returned.

We can define more than one route parameter with the slashes.

For instance, we can write:

const fastify = require('fastify')()

fastify.get('/example/near/:lat-:lng/radius/:r', (request, reply) => {
  reply.send('example')
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

to add the :lat-lng and :r route parameters.

And we can do the same with regex:

const fastify = require('fastify')()

fastify.get('/example/at/:hour(^d{2})h:minute(^d{2})m', (request, reply) => {
  reply.send('example')
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

Conclusion

We can declare routes with various match patterns with Fastify.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *